package com.stcc.portal.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.stcc.base.handler.ReturnValueHandler;
import com.stcc.portal.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.http.MediaType.valueOf;

/**
 * 描述:MyWebMvcConfigurer
 * 项目名:stcc_gl-parent
 * 包名:com.stcc.portal.config
 * 作者:stcc
 * 创建时间:2021/3/11 10:31
 * 版本:1.0
 */
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    /**
     * 拦截器配置
     * */
    @Autowired
    MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.myInterceptor).addPathPatterns("/**");
    }

    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
        returnValueHandlers.add(new ReturnValueHandler());
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setSupportedMediaTypes(getSupportedMediaTypes());
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        converter.setObjectMapper(objectMapper);
        converter.setPrettyPrint(true);
        converters.add(converter);
        converters.add(new StringHttpMessageConverter());

    }

    private List<MediaType> getSupportedMediaTypes() {
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(valueOf("application/json;charset=UTF-8"));
        supportedMediaTypes.add(valueOf("application/xml;charset=UTF-8"));
        supportedMediaTypes.add(valueOf("application/x-www-form-urlencoded;charset=UTF-8"));
        supportedMediaTypes.add(valueOf("text/html;charset=UTF-8"));
        supportedMediaTypes.add(valueOf("text/plain;charset=UTF-8"));
        supportedMediaTypes.add(valueOf("text/xml;charset=UTF-8"));
        supportedMediaTypes.add(valueOf("text/javascript;charset=UTF-8"));
        return supportedMediaTypes;
    }
}
